package org.road0329.tools.proto_parse_tool.ems;

import org.road0329.tools.proto_parse_tool.ems.dataobject.CdIotUpData;
import org.road0329.tools.proto_parse_tool.utils.DateUtil;
import org.road0329.tools.proto_parse_tool.utils.ProtocolUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

@Component
public class ProtocolCdIotWaterUtil {
    private static Logger logger = LoggerFactory.getLogger(ProtocolCdIotWaterUtil.class);
    private static final short STATUS_OPEN = 0;//阀门 打开
    private static final short STATUS_CLOSE = 1;//阀门 关闭

    public static CdIotUpData parseMessage(byte[] msg) {
        if (msg == null || msg.length < 66) {
            return null;
        }
        CdIotUpData result = new CdIotUpData();
        int index = 8;
        //累积量
        BigDecimal decimalValue = ProtocolUtils.byteToBigDecimal(msg, index, 4, 3);
        result.setCumulant(decimalValue);
        index += 4;

        byte[] status = new byte[3];
        System.arraycopy(msg, index, status, 0, 3);
        index += 3;
        short valveStatus = (short)(status[2] & 0x0F);
        result.setValveStatus(valveStatus);
        result.setRssi(msg[index]);
        index += 1;
        result.setVoltage(ProtocolUtils.byteToFloat(msg, index));
        index +=4;
        result.setTemperature(ProtocolUtils.byteToFloat(msg, index));
        index +=4;

        String meterTime = ProtocolUtils.getStringByBCD(msg, index, 6);


        Date dataTime = DateUtil.StrToDate(meterTime, DateUtil.TIME_LONG_12);
        result.setDataTime(dataTime);
        index += 6;

        index += 8;// 跳过位置
        result.setVersion(ProtocolUtils.getStringByBCD(msg, index, 2));
        index += 2;
        result.setIccid(ProtocolUtils.ascii2String(msg,index , 20));

        short batteryStatus = 0;
        if (!"FF".equalsIgnoreCase(String.format("%02X", status[1]))) {
            if ((status[1] & 0x01) != 0x00) {//电池电压欠压
                batteryStatus = 1;
            }
        }
        result.setBatteryStatus(batteryStatus);

        return result;
    }
}
